from django.db import models
from django.urls import reverse
import uuid
from django.contrib.auth.models import User

class Author(models.Model):
    first_name = models.CharField('名', max_length=100)
    last_name = models.CharField('姓', max_length=100)
    date_of_birth = models.DateField('出生日期', null=True, blank=True)
    date_of_death = models.DateField('去世日期', null=True, blank=True)

    class Meta:
        ordering = ['last_name', 'first_name']
        verbose_name = '作者'
        verbose_name_plural = '作者'

    def get_absolute_url(self):
        return reverse('author-detail', args=[str(self.id)])

    def __str__(self):
        return f'{self.last_name}, {self.first_name}'

class Book(models.Model):
    title = models.CharField('书名', max_length=200)
    author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True, verbose_name='作者')
    summary = models.TextField('简介', max_length=1000, help_text='请输入本书简介')
    isbn = models.CharField('ISBN', max_length=13, help_text='13位ISBN号')

    class Meta:
        verbose_name = '书籍'
        verbose_name_plural = '书籍'

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('book-detail', args=[str(self.id)])

class BookInstance(models.Model):
    id = models.UUIDField('ID', primary_key=True, default=uuid.uuid4, help_text='唯一ID')
    book = models.ForeignKey('Book', on_delete=models.RESTRICT, null=True, verbose_name='书籍')
    imprint = models.CharField('出版社信息', max_length=200)
    due_back = models.DateField('归还日期', null=True, blank=True)
    borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='借用人')
    LOAN_STATUS = (
        ('m', '维护中'),
        ('o', '已借出'),
        ('a', '可用'),
        ('r', '已预订'),
    )
    status = models.CharField('状态', max_length=1, choices=LOAN_STATUS, blank=True, default='m', help_text='图书可用状态')

    class Meta:
        ordering = ['due_back']
        verbose_name = '借阅记录'
        verbose_name_plural = '借阅记录'

    def __str__(self):
        return f'{self.id} ({self.book.title})'
